<?php
/**
 * 通用导出数据基类
 * User：liujun
 * Date：2022/9/1
 * Time：16:23
 */

namespace Encore\Admin\Actions\Custom;

use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\WithMapping;

class BaseExporter extends ExcelExporter implements WithMapping
{
    protected $columns = [];
    protected $fileName = '导出文件.xlsx';

    public function __construct(Grid $grid = null)
    {
        [$name, $ext] = explode('.', $this->fileName);
        $this->fileName = $name . '_' . date('YmdHis') . '.' . $ext;
        parent::__construct($grid);
    }

    /**
     * @param $row
     * @return array
     * @throws \Throwable
     */
    public function map($row): array
    {
        $this->authorize();
        $map = [];
        foreach ($this->columns as $key => $name) {
            $map[$key] = $this->rewrite($key, data_get($row, $key), $row);
        }
        return $map;
    }

    /**
     * 重写字段
     * @param $key
     * @param $val
     * @param Model $row
     * @return string|null
     */
    public function rewrite($key, $val, Model $row): ?string
    {
        return is_numeric($val) ? $val : $val . ' ';
    }

    /**
     * 验证是否有导出数据权限
     * @return void
     * @throws \Throwable
     */
    public function authorize()
    {
        $action = Str::of(static::class)->afterLast('\\')->snake('.');
        //throw_if(!Model::adminUser()->can($action), new \Exception('无导出数据权限'));
    }
}